package com.site.common.aspect;

import com.site.common.annotation.Login;
import com.site.common.exception.BusinessException;
import com.site.util.JwtTokenUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 *  Auth 登录权限
 */
public class LoginAspect extends AbstractAspect {
    private static Logger logger = LoggerFactory.getLogger(RateLimiterAspect.class);

    private static final String TOKEN = "Authorization";

    @Override
    protected Object execute(ProceedingJoinPoint joinPoint, Method method, HttpServletRequest request) {
        Login login = method.getAnnotation(Login.class);
        if (login.isLogin()){
            String token = request.getHeader(TOKEN);
            if (token == null){
                token = request.getParameter(TOKEN);
            }
            if (token == null || "".equals(token)){
                logger.info("<<================= Authorization不存在!,请求地址:{}",request.getRequestURI());
                throw new BusinessException("Authorization不存在!");
            }
            if (!JwtTokenUtil.check(token)){
                logger.info("<<================= Authorization不合法!,请求地址:{}",request.getRequestURI());
                throw new BusinessException("Authorization不合法!");
            }
            if (JwtTokenUtil.isTokenExpired(token)){
                logger.info("<<================= Authorization无效!,请求地址:{}",request.getRequestURI());
                throw new BusinessException("Authorization无效!");
            }
        }
        if (login.required() || login.scope() > 0){
            // 根据实际需求进行验证
        }
        return null;
    }
}
